package com.android.allwinner.newaw360.media;

import android.app.Service;
import android.content.Intent;
import android.hardware.Camera;
import android.media.CamcorderProfile;
import android.media.MediaRecorder;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.provider.SyncStateContract;
import android.support.annotation.Nullable;
import android.util.Log;
import android.widget.Toast;

import com.android.allwinner.newaw360.R;
import com.android.allwinner.newaw360.common.APPConfig;
import com.android.allwinner.newaw360.storage.AW360StorageManager;
import com.android.allwinner.newaw360.task.DeleteFileTask;
import com.android.allwinner.newaw360.utils.AW360SharePreferenceUtil;
import com.android.allwinner.newaw360.utils.DateTimeUtil;
import com.android.allwinner.newaw360.utils.LogUtil;
import com.android.allwinner.newaw360.utils.SDCardUtils;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * Created by xiasj on 17-6-14.
 */

public class AW360MediaService extends Service implements MediaRecorder.OnErrorListener, MediaRecorder.OnInfoListener {
    private static final String TAG = AW360MediaService.class.getSimpleName();
    public static final int MESSAGE_VIDEO_PATH_UNUSE = 1;
    public static final int MESSAGE_START_RECORDER = 2;
    public static final int MESSAGE_STOP_RECORDER = 3;
    public static final int MESSAGE_NEXT_SAVE_FILE = 4;
    public static final int MESSAGE_NO_SDCARD=5;
    private MediaRecorder mMediaRecorder;
    private final IBinder mBinder = new LocalBinder();
    private Camera mCamera;
    private Handler mHandler;
    private boolean isRecording;
    private String filePath;


    public boolean isRecording(){
        return isRecording;
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return mBinder;
    }

    @Override
    public boolean onUnbind(Intent intent) {
        LogUtil.i(TAG, "----onUnbind");
        if (isRecording) {
            stopRecorder();
        }
        return super.onUnbind(intent);
    }

    @Override
    public void onError(MediaRecorder mr, int what, int extra) {
        stopRecorder();
    }

    @Override
    public void onInfo(MediaRecorder mr, int what, int extra) {
        filePath = createFilePath();
        setNextSaveFile(filePath);
        sendMessage(MESSAGE_NEXT_SAVE_FILE, 0);
    }

    class LocalBinder extends Binder {
        public AW360MediaService getService() {
            return AW360MediaService.this;
        }
    }

    protected void setNextSaveFile(String path) {
        if (mMediaRecorder == null) {
            stopRecorder();
            return;
        }
        try {
         /*   if (!checkStorageSpace()) {
                sendMessage(MESSAGE_VIDEO_PATH_UNUSE, 0);
                return;
            }*/
            checkStorageSpace();
            Class cls = Class.forName("android.media.MediaRecorder");
            Method setNextSaveFile = cls.getMethod("setNextSaveFile", String.class);
            setNextSaveFile.invoke(mMediaRecorder, path);
        } catch (NoSuchMethodException e) {
            stopRecorder();
            LogUtil.e(TAG, "The system haven't this method");
        } catch (ClassNotFoundException e) {
            stopRecorder();
            LogUtil.e(TAG, "The system haven't this class");
        } catch (IllegalAccessException e) {
            stopRecorder();
            LogUtil.e(TAG, "The system haven't this method");
        } catch (InvocationTargetException e) {
            stopRecorder();
            LogUtil.e(TAG, "The system haven't this method");
        }
    }

    public void startRecorder(Camera camera, Handler handler) {
        LogUtil.i(TAG, "----------------startRecorder");
        if (isRecording) {
            return;
        }

        if (!checkStorageSpace()) {
            return;
        }

        filePath = createFilePath();
        mCamera = camera;
        mHandler = handler;
        initializeRecorder();

        if (mMediaRecorder != null) {
            LogUtil.i(TAG, "MediaRecord is not null");
        } else {
            LogUtil.i(TAG, "MediaRecord is null");
        }

        if (mMediaRecorder != null) {
            try {
                mMediaRecorder.start();
                sendMessage(MESSAGE_START_RECORDER, 0);
                isRecording = true;
            } catch (RuntimeException e) {
                releaseMediaRecorder();
                LogUtil.e(TAG, "MediaRecord.start()-- " + e.getMessage());
            }
        } else {
            releaseMediaRecorder();
        }
    }

    public boolean stopRecorder() {
        LogUtil.i(TAG, "----------------stopRecorder");
        if (!isRecording) {
            return true;
        }
        mMediaRecorder.stop();
        releaseMediaRecorder();
        isRecording = false;
        sendMessage(MESSAGE_STOP_RECORDER, 0);
        return true;
    }

    private void initializeRecorder() {
        mMediaRecorder = new MediaRecorder();// 创建mediarecorder对象
        if (mCamera == null) {
            LogUtil.i(TAG, "mCamera == null");
            return;
        }
        // 解锁camera
        mCamera.unlock();
        mMediaRecorder.setCamera(mCamera);
        // mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.CAMCORDER);
        mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
        // 设置录制文件质量，格式，分辨率之类，这个全部包括了
        CamcorderProfile profile = CamcorderProfile.get(CamcorderProfile.QUALITY_HIGH);
        mMediaRecorder.setOutputFormat(profile.fileFormat);
        LogUtil.i(TAG, "----------setOutputFormat   =" + profile.fileFormat);
        mMediaRecorder.setVideoFrameRate(profile.videoFrameRate);
        LogUtil.i(TAG, "----------videoFrameRate   =" + profile.videoFrameRate);

        LogUtil.i(TAG, "----------setVideoSize   1440x960");
        mMediaRecorder.setVideoSize(1440, 960);


        LogUtil.i(TAG, "----------------profile.videoBitRate = "
                + profile.videoBitRate);
        mMediaRecorder.setVideoEncodingBitRate(profile.videoBitRate);
//        mMediaRecorder.setVideoEncodingBitRate(4000000);

        LogUtil.i(TAG, "----------videoCodec   =" + profile.videoCodec);
        mMediaRecorder.setVideoEncoder(profile.videoCodec);
        LogUtil.i(TAG, "audioChannels=" + profile.audioChannels);
        // mMediaRecorder.setPreviewDisplay(surfaceHolder.getSurface());
        mMediaRecorder.setMaxDuration(Integer.valueOf(AW360SharePreferenceUtil.getVideoDuration()));
        mMediaRecorder.setMaxFileSize(0);
        // 设置视频文件输出的路径
        mMediaRecorder.setOutputFile(filePath);
        mMediaRecorder.setOnErrorListener(this);
        mMediaRecorder.setOnInfoListener(this);
        try {
            // 准备录制
            mMediaRecorder.prepare();
        } catch (IllegalStateException e) {
            LogUtil.e(TAG, "IllegalStateException");
            releaseMediaRecorder();
            LogUtil.e(TAG, e.getMessage());
        } catch (IOException e) {
            LogUtil.e(TAG, "IOException");
            releaseMediaRecorder();
            LogUtil.e(TAG, e.getMessage());
        }
    }

    private void releaseMediaRecorder() {
        if (mMediaRecorder != null) {
            mMediaRecorder.reset();
            mMediaRecorder.release();
            mMediaRecorder = null;
        }
    }

    private void sendMessage(int message, int time) {
        if (mHandler != null) {
            mHandler.sendEmptyMessageDelayed(message, time);
        }
    }

    private boolean checkStorageSpace() {
        if (!SDCardUtils.isPathEnable(AW360SharePreferenceUtil.getVideoPath())) {
            sendMessage(MESSAGE_NO_SDCARD, 0);
            LogUtil.e(TAG, "checkStorageSpace ---------> this path not enable!!!");
            return false;
        } else {
            if (SDCardUtils.getFreeBytes(AW360SharePreferenceUtil.getVideoPath()) < APPConfig.SMALL_FREE_SIZE) {
                LogUtil.e(TAG, "checkStorageSpace -------> storage not enough!!!");
                sendMessage(MESSAGE_VIDEO_PATH_UNUSE, 0);
                new DeleteFileTask().execute();
                return false;
            }
        }
/*        //TODO 漏秒情况下，可统一在startRecord处检测存储空间是否充足---低于300M触发
        if (!APPConfig.IS_PREALLOCATE) {
            LogUtil.i(TAG, "checkStorageSpace -------> Run DeleteRileTask!");
            new DeleteFileTask().execute();
        }*/
        return true;
    }

    private String createFilePath(){
        String title = createFileName();
        String fileName = title + ".mp4";
        String filePath = AW360SharePreferenceUtil.getVideoPath() + fileName;
        return filePath;
    }

    private String createFileName(){
        return "VID_" + DateTimeUtil.getCurrentNumberDateTime();
    }


 /*   *//*自动从后面重命名文件*//*
    private void clearSDStorage(){
        renameLastFile();
        while (!checkStorageSpace()) {
            renameLastFile();
        }
    }

    private void renameLastFile(){
        AW360StorageManager aw360StorageManager = new AW360StorageManager();
        List<MediaFileInfo> curMediaFileInfos = aw360StorageManager.getVideoFiles(Constants.VIDEO_DIRECTORY);
        if (curMediaFileInfos != null && curMediaFileInfos.size() > 0) {
            LogUtil.d(TAG, "rename" + curMediaFileInfos.get(curMediaFileInfos.size() - 1).getPath());
            LogUtil.d(TAG, "rename" + curMediaFileInfos.get(curMediaFileInfos.size() - 2).getPath());
            File file1 = new File(curMediaFileInfos.get(curMediaFileInfos.size() - 1).getPath());
            file1.renameTo(new File(filePath));
            File file2 = new File(curMediaFileInfos.get(curMediaFileInfos.size() - 2).getPath());
            file2.renameTo(new File(filePath));
         *//* file.delete();*//*
            LogUtil.d(TAG, "renameTo =" + filePath);
        }
    }*/

}
